import request from '../utils/request'

// Dify API配置
const DIFY_API_KEY = import.meta.env.VITE_DIFY_API_KEY

// 用于存储当前活跃的请求和状态控制
let activeRequest = null;
let isDialogueActive = false;
let requestLock = false;

// 清理和修复 JSON 字符串的更强大版本
const sanitizeAndFixJson = (str) => {
  try {
    // 基础清理
    let cleaned = str
      .replace(/[\u0000-\u001F]+/g, '')       // 移除控制字符
      .replace(/\\'/g, "'")                    // 处理单引号
      .replace(/\\"/g, '\\"')                  // 修复双引号转义
      .replace(/\t/g, ' ')                     // 替换制表符
      .replace(/\n/g, ' ')                     // 替换换行符
      .trim();

    // 检查基本的 JSON 结构
    if (!cleaned.startsWith('{') && !cleaned.startsWith('[')) {
      console.debug('无效的JSON结构:', cleaned);
      return null;
    }

    // 修复 JSON 格式问题
    cleaned = cleaned
      // 处理属性名中的引号问题
      .replace(/([{,]\s*)(\w+)(\s*:)/g, '$1"$2"$3')
      // 修复属性值的引号问题
      .replace(/:\s*'([^']*?)'/g, ':"$1"')
      // 移除多余的逗号
      .replace(/,\s*([\]}])/g, '$1')
      .replace(/,\s*,/g, ',')
      // 修复布尔值
      .replace(/:\s*(True|False)\s*([,}])/g, (_, val, end) => 
        ': ' + val.toLowerCase() + end)
      // 修复 null/undefined/None 值
      .replace(/:\s*(null|undefined|None)\s*([,}])/gi, ':null$2')
      // 修复数值
      .replace(/:\s*([+-]?\d+\.?\d*)\s*([,}])/g, ':$1$2')
      // 修复字符串值
      .replace(/:\s*([^",}\]\s]+)(\s*[,}])/g, ':"$1"$2')
      // 修复数组格式
      .replace(/\[\s*,/g, '[')
      .replace(/,\s*\]/g, ']')
      // 处理未闭合的括号
      .replace(/([^}\]"\d])\s*$/g, '$1}');

    // 验证括号配对
    let stack = [];
    let inString = false;
    let escaped = false;

    for (let i = 0; i < cleaned.length; i++) {
      const char = cleaned[i];
      
      if (char === '"' && !escaped) {
        inString = !inString;
      } else if (!inString) {
        if (char === '{' || char === '[') {
          stack.push(char);
        } else if (char === '}' && stack[stack.length - 1] === '{') {
          stack.pop();
        } else if (char === ']' && stack[stack.length - 1] === '[') {
          stack.pop();
        }
      }
      
      escaped = char === '\\' && !escaped;
    }

    // 补充缺失的闭合括号
    while (stack.length > 0) {
      const lastChar = stack.pop();
      cleaned += lastChar === '{' ? '}' : ']';
    }

    // 最终验证
    try {
      const parsed = JSON.parse(cleaned);
      if (parsed && typeof parsed === 'object') {
        return cleaned;
      }
    } catch (finalError) {
      console.debug('最终验证失败:', finalError);
      return null;
    }

    return null;
  } catch (error) {
    console.debug('JSON 清理过程出错:', error);
    return null;
  }
};

// 处理流式响应数据
const handleStreamData = (chunk) => {
  if (!chunk.trim() || !chunk.startsWith('data: ')) {
    return null;
  }

  try {
    const cleanData = chunk.slice(6).trim();
    if (!cleanData || cleanData === 'null' || cleanData === 'undefined') {
      return null;
    }

    // 首先尝试直接解析
    try {
      return JSON.parse(cleanData);
    } catch (initialError) {
      // 如果直接解析失败，使用增强的修复方法
      const fixedData = sanitizeAndFixJson(cleanData);
      if (fixedData) {
        return JSON.parse(fixedData);
      }
    }
  } catch (error) {
    console.warn('解析消息块失败:', error);
    return null;
  }

  return null;
};

// 取消当前对话
export function cancelCurrentDialogue() {
  if (activeRequest) {
    activeRequest.abort();
    activeRequest = null;
  }
  isDialogueActive = false;
  requestLock = false;
}

// 保存聊天历史
export function saveChat(messages) {
  const timestamp = Date.now();
  const chatSession = {
    id: timestamp,
    timestamp,
    messages: [...messages]
  };
  
  // 从本地存储获取现有历史
  let history = [];
  try {
    const savedHistory = localStorage.getItem('difyChatHistory');
    if (savedHistory) {
      history = JSON.parse(savedHistory);
    }
  } catch (e) {
    console.error('读取历史失败:', e);
  }
  
  // 添加新会话到历史
  history.unshift(chatSession);
  
  // 限制历史记录数量（保留最新的20条）
  if (history.length > 20) {
    history = history.slice(0, 20);
  }
  
  // 保存到本地存储
  localStorage.setItem('difyChatHistory', JSON.stringify(history));
  
  return chatSession;
}

// 创建聊天消息
export function createChatMessage(message, conversationId = null, files = [], onStream = null) {
  // 如果当前有活跃对话或请求被锁定，拒绝新的请求
  if (isDialogueActive || requestLock) {
    console.debug('当前已有活跃对话或请求被锁定');
    return Promise.reject(new Error('当前对话尚未完成，请等待'));
  }

  // 锁定请求和标记对话为活跃状态
  requestLock = true;
  isDialogueActive = true;

  // 创建新的 AbortController
  const controller = new AbortController();
  activeRequest = controller;

  // 用于追踪消息状态
  let messageBuffer = {
    content: '',
    lastUpdate: Date.now(),
    messageId: null,
    isDone: false,
    lastChunk: ''
  };

  const requestPromise = request({
    url: '/chat-messages',
    method: 'post',
    headers: {
      'Authorization': `Bearer ${DIFY_API_KEY}`,
      'Content-Type': 'application/json',
      'Accept': 'text/event-stream'
    },
    data: {
      inputs: {},
      query: message,
      response_mode: 'streaming',
      conversation_id: conversationId || '', // 确保conversation_id被正确传递
      user: 'web-user',
      files: files
    },
    signal: controller.signal,
    responseType: 'text',
    timeout: 180000, // 3分钟超时
    onDownloadProgress: (progressEvent) => {
      if (!onStream || messageBuffer.isDone) return;

      try {
        const rawText = progressEvent.event.target.responseText;
        const newText = rawText.slice(messageBuffer.lastChunk.length);
        const chunks = newText.split('\n\n');
        
        for (const chunk of chunks) {
          const data = handleStreamData(chunk);
          if (!data) continue;
          
          if (data.conversation_id && !messageBuffer.conversationId) {
            messageBuffer.conversationId = data.conversation_id;
            // 传递conversation_id给回调
            onStream({
              event: 'conversation_id',
              conversation_id: data.conversation_id
            });
          }

          if (data.event === 'agent_message' && data.answer) {
            messageBuffer.content = data.answer.trim();
            messageBuffer.lastUpdate = Date.now();
            
            if (!messageBuffer.isDone) {
              onStream({
                event: 'agent_message',
                answer: messageBuffer.content,
                messageId: messageBuffer.messageId || data.message_id,
                conversation_id: messageBuffer.conversationId
              });
            }
          } else if (data.event === 'message_replace' && data.answer) {
            messageBuffer.content = data.answer.trim();
            messageBuffer.lastUpdate = Date.now();
            
            if (!messageBuffer.isDone) {
              onStream({
                event: 'message_replace',
                answer: messageBuffer.content,
                messageId: messageBuffer.messageId || data.message_id,
                conversation_id: messageBuffer.conversationId
              });
            }
          } else if (data.event === 'done') {
            messageBuffer.isDone = true;
            isDialogueActive = false;
            requestLock = false;
            activeRequest = null;
            
            if (messageBuffer.content) {
              onStream({
                event: 'done',
                answer: messageBuffer.content,
                messageId: messageBuffer.messageId,
                conversation_id: messageBuffer.conversationId
              });
            }
          }
        }

        messageBuffer.lastChunk = rawText;
      } catch (error) {
        console.error('处理流式响应失败:', error);
        isDialogueActive = false;
        requestLock = false;
      }
    }
  });

  // 确保在请求完成后重置所有状态
  requestPromise.finally(() => {
    isDialogueActive = false;
    requestLock = false;
    if (activeRequest === controller) {
      activeRequest = null;
    }
  });

  // 添加超时处理
  setTimeout(() => {
    if (isDialogueActive && !messageBuffer.isDone) {
      cancelCurrentDialogue();
      onStream?.({
        event: 'done',
        answer: messageBuffer.content || '对话超时，请重试',
        messageId: messageBuffer.messageId
      });
    }
  }, 180000); // 3分钟超时

  return requestPromise;
}

// 添加一个新的方法用于发送带图片的消息
export function createChatMessageWithImage(message, imageUrl, conversationId = null) {
  const files = [{
    type: 'image',
    transfer_method: 'remote_url',
    url: imageUrl
  }]
  
  return createChatMessage(message, conversationId, files)
}

// 获取消息历史
export function getChatHistory(conversationId) {
  return request({
    url: '/messages',
    method: 'get',
    headers: {
      'Authorization': `Bearer ${DIFY_API_KEY}`
    },
    params: {
      conversation_id: conversationId
    }
  })
}
